const xy = require('../utils/xy')
const authModel = require('../db/auth')
const tidyAuthList = require('../utils/tidyAuthList')
const writeErr = require('../utils/writeErr')

module.exports = {
    async add(req, resp) {
        let {name, path, parentId, icon, isShow} = req.body
        if(!name || !path || !parentId || !icon || isShow === undefined) {
            xy(resp, 401, '缺少参数')
            return
        }
        console.log(name, path, parentId, icon, isShow);
        try{
            await authModel.insertMany(req.body)
            xy(resp, 200, '权限新增成功')
        } catch(err) {
            writeErr(err)
            xy(resp, 512, '权限新增失败！')
        }
    },
    async list(req, resp) {
        try{
            let authlist = await authModel.find()
            // 递归组合所有权限
            authlist = tidyAuthList(authlist)
            xy(resp, 200, '权限列表获取成功！', {
                authlist
            })
        }catch(err) {
            writeErr(err)
            xy(resp, 513, '权限列表获取失败！')
        }
    },
    async edit(req, resp) {
        let {id} = req.params
        let {name, parentId, path, icon, isShow} = req.body
        console.log(req.body);
        if(!name || !parentId || !path || !icon || isShow === undefined) {
            xy(resp, 401, '缺少参数！')
            return
        }
        try{ 
            await authModel.updateOne({_id: id}, req.body)
            xy(resp, 200, '权限修改成功！')
        }catch(err) {
            writeErr(err)
            xy(resp, 524, '权限修改失败！')
        }
    },
    async authStatus(req, resp) {
        let {id} = req.params
        try{
            let auth = await authModel.findOne({_id: id})
            try{
                await authModel.updateOne({_id: id}, {isShow: !auth.isShow})
                xy(resp, 200, '权限状态修改成功！')
            } catch(err) {
                writeErr(err)
                xy(resp, 525, '权限状态修改失败！')
            }
        } catch(err) {
            writeErr(err)
            xy(resp, 525, '权限状态修改失败！')
        }
    },
    async del(req, resp) {
        let {id} = req.params
        try{
            await authModel.deleteOne({_id: id})
            xy(resp, 200, '权限删除成功！')
        } catch(err) {
            writeErr(err)
            xy(resp, 526, '权限删除失败')
        }
    }
}